<template>
<div class="box">
    <div class="header">
        <h1>短信验证登录/注册</h1>
        <p>新手机号将自动注册，请想读<span>豆瓣使用协议</span></p>
    </div>
     <div class="main">
        <van-form @submit="onSubmit">
  <van-cell-group inset>
    <van-field
      v-model="username"
      name="username"
      label="+86"
      placeholder="手机号"
      :rules="[{ required: true, message: '请填写手机号' },,{pattern:/^1[3-9]\d{9}$/,message:'请输入11位手机号'}]"
    />
   
   <van-field
    v-model="sms"
    center
    clearable
    label="短信验证码"
    placeholder="请输入短信验证码"
  :rules="[{ required: true, message: '请填写验证码' },{pattern:/^\d{6}$/,message:'请输入6位验证码'}]"
  >
    <template #button>
      <van-button size="small" @click="second" :disabled="msg!='获取验证码'">{{msg}}</van-button>
    </template>
  </van-field>
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      登录
    </van-button>
  </div>
</van-form>
 <div class="text">
     <p>账号密码登录</p>
     <p @click="$router.push('/register')">手机号快速注册</p>
 </div>
 <div class="img">
     <p class="nh1">第三方登录</p>
      <div class="imging">
        <p><img src="../../img/1.jpg" alt=""></p>
         <p><img src="../../img/2.jpg" alt=""></p>
      </div>
 </div>
     </div>
    </div>
</template>

<script setup >
import {ref} from 'vue'
import request from '@/utils/request'
import {useRouter} from 'vue-router'
import { showSuccessToast, showFailToast } from 'vant';
const router = useRouter()
const username=ref('')
const sms=ref('')
const count = ref(60)
const timer = ref(null)
const msg = ref('获取验证码')
const onSubmit=(values)=>{
    request.post('/login',{
        username:username.value,
        sms:sms.value
    }).then(res=>{
        if(res.data.code==200)
        {
            showSuccessToast(res.data.message);
            localStorage.setItem('token',res.data.token)
             localStorage.setItem('username',username.value)
            router.push('/user')
        }else{
            showFailToast(res.data.message);
        }
    })
}

const second=()=>{
   request.get('/code').then(res=>{
        sms.value=res.data.data
   })
   msg.value=count.value+'秒回重新发送'
   timer.value = setInterval(()=>{
     count.value--
     if(count.value===0)
     {
        clearInterval(timer.value)
        msg.value='获取验证码'
        count.value=60
     }else{
        msg.value=count.value+'秒后重新发送'
     }
   },1000)
}
</script>





<style lang="scss" scoped>
.header{
   
   margin-left: 10%;
   span{
    color: #1cb93a;
   }
}
.text{
    display: flex;
    justify-content: space-between;
    padding: 20px;
    font-size: 12px;
}
.img{
    width: 200px;
    height: 200px;
    margin-left: 30%;
   
    .nh1{
        margin-left: 60px;
    }
    .imging{
        display: flex;
    justify-content: space-between;
     img{
        width: 50px;
        height: 50px;
        margin: 10px;
     }
    }
}
</style>